package com.gjintel.framework.login.controller;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.ahca.cn.pkiservice.ahcapkiservers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.framework.constant.ActivitiMap;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.register.model.DepositCategory;
import com.gjintel.framework.register.model.RegisterCategory;
import com.gjintel.framework.register.model.RegisterUser;
import com.gjintel.framework.register.service.IRegisterUserService;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.role.model.Role;
import com.gjintel.framework.role.service.IRoleService;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.user.model.UserRole;
import com.gjintel.framework.user.service.IUserService;
import com.gjintel.sdk.util.MD5Lock;


@RequestMapping("/user-login-sys-new")
@Controller
public class UserLoginSysController1 {

	@Autowired
	private IUserService userService;
	@Autowired
	private IRegisterUserService registerUserService;
	
	@Autowired
	private IRoleService roleService;
	
	
	
	/**
	 * @description 进入密码登录页面
	 * @mv
	 * @author shy
	 */
	@RequestMapping("/loginPwd")
	public ModelAndView loginPwd(){
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/login/login-pwd");
 		return mv;
	}

	/**
	 * @description 进入CA登录页面
	 * @mv
	 * @author shy
	 */
	@RequestMapping("/loginCA")
	public ModelAndView loginCA(){
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/login/login-ca");
 		return mv;
	}

	/**
	 * @author shy
	 * @description 用户登录 
	 */
	
	@RequestMapping("/calogin")
	@ResponseBody
	public String calogin(HttpSession session, String signData,String certData,String caCard){
		User loginUser = null;
		RegisterUser registerUser = null;
		List<RegisterUser> registerUsers = this.registerUserService.regcaLogin(caCard);
		List<User> users = this.userService.caLogin(caCard);
		if (users.isEmpty()) {
			if (registerUsers.isEmpty()) {
				return Constant.USER_NO_EXIST;//用户不存在
			} else {
				registerUser = registerUsers.get(0);
				try {
					String strSOAPServer = Constant.getSOAPServerPath();
					String[] verifycert = new ahcapkiservers().ServerVClient( strSOAPServer , certData , signData );
					if(verifycert != null && !"1".equals(verifycert[0])){
						return verifycert[1];
					}
				} catch (Exception e) {
					return "请求签名服务器失败！";
				}
              	if(registerUser.getFlag()!=1){
              		session.setAttribute("registerUser", registerUser);
    				return Constant.REGISTER_UN_PASS_AUDIT;//审核不通过
              	}	
				
			}
		} else {
			loginUser = users.get(0);
		}
		try {
			String strSOAPServer = Constant.getSOAPServerPath();
			String[] verifycert = new ahcapkiservers().ServerVClient( strSOAPServer , certData , signData );
			if(verifycert != null && !"1".equals(verifycert[0])){
				return verifycert[1];
			}
		} catch (Exception e) {
			return "请求签名服务器失败！";
		}
		
		if (registerUsers.size()>0){ //用户修改后未审核，或审核不同过
			registerUser=registerUsers.get(0);
			if(registerUser.getFlag()!=1){
				session.setAttribute("registerUser", registerUser);
				return Constant.REGISTER_UN_PASS_AUDIT;
			}	
		}
		List<Role> roleList = this.userService.getUserRole(loginUser.getId());
		if (!roleList.isEmpty()) {
			session.setAttribute("loginUserRole", roleList);
		}
		// 把登录用户信息写入到session中
		session.setAttribute("loginUser", loginUser);
		if(loginUser.getLoginTime() != null){
			loginUser.setLastLoginTime(loginUser.getLoginTime());
		}
		loginUser.setLoginTime(new Date());
		this.userService.saveOrUpdate(loginUser);
		return Constant.USER_LOGIN_SUCCESS;
	}

	@RequestMapping("/userlogin")
	@ResponseBody
	public String userlogin(HttpSession session, String loginName, String passWord) {
		User loginUser = null;
		RegisterUser registerUser = null;
		List<RegisterUser> registerUsers=this.registerUserService.getLoginRegisterUserByLoginName(loginName);
		List<User> users = this.userService.getLoginUser(loginName);
		if (users.size()<1) {	
		    if (registerUsers.isEmpty()) {
		    	return Constant.USER_NO_EXIST;//用户不存在
			} else {
				for (RegisterUser regUser : registerUsers) {
						if (regUser.getPwd().equals(MD5Lock.lock(passWord.trim()))) {
							registerUser = regUser;
					}
				}
				if (registerUser==null) {
					return Constant.PSW_NO_RIGNT;
				}
//				else if (registerUser.getLoginTypePWD()==0)  {  // 用户名/密码登录方式被禁用
//					return Constant.LOGIN_TYPE_ERROR;
//					}
				else if(registerUser.getFlag()!=1){
					session.setAttribute("registerUser", registerUser);
					
					return Constant.REGISTER_UN_PASS_AUDIT;
				}
	
			}
		}
		for (User user : users) {
			if (user.getPsw().equals(MD5Lock.lock(passWord.trim()))) {
				loginUser = user;			
//				UserRole roleBidder= roleService.findUserRole(ActivitiMap.BIDDER_ID,user.getId());
//				if (roleBidder==null) { //非投标人不能使用密码登录
//					return Constant.CHANGE_LOGIN_TYPE;
//				}
			}
		}
		
		if (registerUsers.size()>0){ //用户修改后未审核，或审核不同过
			for (RegisterUser regUser : registerUsers) {
				if (regUser.getPwd().equals(MD5Lock.lock(passWord.trim()))) {
					registerUser = regUser;
			}
		}
			if(registerUser==null){
				   return Constant.PSW_NO_RIGNT;
			}else {
				if(registerUser.getFlag()!=1){
					session.setAttribute("registerUser", registerUser);
					return Constant.REGISTER_UN_PASS_AUDIT;
				}	
			}	
		}
		if (loginUser == null) {
			return Constant.PSW_NO_RIGNT;
		}
//		else if (loginUser.getLoginPWD()==0) {   // 用户名/密码登录方式被禁用
//			return Constant.LOGIN_TYPE_ERROR;
//		}
		else {
			session.setAttribute("loginUser", loginUser);
			List<Role> roleList = this.userService.getUserRole(loginUser.getId());
			if (!roleList.isEmpty()) {
				session.setAttribute("loginUserRole", roleList);
			}
			if(loginUser.getLoginTime() != null){
				loginUser.setLastLoginTime(loginUser.getLoginTime());
			}
			loginUser.setLoginTime(new Date());
			this.userService.saveOrUpdate(loginUser);
			return Constant.USER_LOGIN_SUCCESS;	
		}
	}
		
		
	

	@RequestMapping("/downFile")
	public void downFile(HttpSession session,HttpServletResponse res) throws IOException{
		PrintWriter out = res.getWriter();
		res.setCharacterEncoding("utf-8");
		res.setContentType("multipart/form-data");
        res.setHeader("Content-Disposition", "attachment;fileName=test.html");
		FileReader fr = null;
		fr = new FileReader(new File(session.getServletContext().getRealPath("/login/"),"test.html"));
		char[] cach = new char[1024];
		int index = -1;
		while((index = fr.read(cach)) != -1){
			out.write(cach,0,index);
			out.flush();
		}
		out.close();
	}
	
	@RequestMapping("/outSys")
	@ResponseBody
	public String outSys(HttpSession session) {
		session.invalidate();
		return Constant.SUCCESS;
	}
	
	
	/**
	 * @description 获取注册用户信息（审核未通过）
	 * @author shy
	 */
	@RequestMapping("/unPassRegisterInfo")
	@ResponseBody
	public ModelAndView getUnPassRegister(HttpSession session) {
		ModelAndView mv = new ModelAndView();
		RegisterUser  register =(RegisterUser) session.getAttribute("registerUser");
		RegisterUser rUser = registerUserService.getRegisterById(register.getId());
		Resources resources = new Resources();
		resources = this.registerUserService.get(Resources.class, rUser.getImage01());
		Resources resources2 = new Resources();
		resources2 = this.registerUserService.get(Resources.class, rUser.getImage02());
		Resources resources3 = new Resources();
		resources3 = this.registerUserService.get(Resources.class, rUser.getImage03());
		Resources resources4 = new Resources();
		resources4 = this.registerUserService.get(Resources.class, rUser.getImage04());
		Resources resources5 = new Resources();
		resources5 = this.registerUserService.get(Resources.class, rUser.getImage05());
		String DepositCategoryData = registerUserService.getDepositCategoryName(rUser.getId());
		List<DepositCategory> depositCategoryList = registerUserService.getDepositCategoryById(rUser.getId());
		mv.addObject("depositCategoryList", depositCategoryList);
		mv.addObject("depositCategory", DepositCategoryData);
		mv.addObject("register", rUser);
		mv.addObject("image01", resources);
		mv.addObject("image02", resources2);
		mv.addObject("image03", resources3);
		mv.addObject("image04", resources4);
		mv.addObject("image05", resources5);
		if(rUser.getFlag()==2){
			mv.setViewName("register/register-unPass-Info");
		}
		if(rUser.getFlag()==0){
			mv.setViewName("register/register-unAudit-Info");
		}
		
		return mv;
	}



	/**
	 * @description 修改注册用户信息(register)
	 * @author shy
	 */
	@RequestMapping("/editPage")
	@ResponseBody
	public ModelAndView editPage(HttpSession session) {
		ModelAndView mv = new ModelAndView();
		RegisterUser  register =(RegisterUser) session.getAttribute("registerUser");
		RegisterUser rUser = registerUserService.getRegisterById(register.getId());
		
		Resources resources = new Resources();	
		String image01Path="";
		resources = this.registerUserService.get(Resources.class, rUser.getImage01());
		if(resources !=null){
			 image01Path = resources.getFilePath() + File.separator + resources.getId()+ resources.getExeName();	
		}
		
		Resources resources2 = new Resources();
		String image02Path="";
		resources2 = this.registerUserService.get(Resources.class, rUser.getImage02());
		if(resources2 !=null){
		  image02Path = resources2.getFilePath() + File.separator + resources2.getId()+ resources2.getExeName();
		}
		Resources resources3 = new Resources();
		String image03Path="";
		resources3 = this.registerUserService.get(Resources.class, rUser.getImage03());
		if(resources3 !=null){
		image03Path = resources3.getFilePath() + File.separator + resources3.getId()+ resources3.getExeName();
		}
		Resources resources4 = new Resources();
		String image04Path="";
		resources4 = this.registerUserService.get(Resources.class, rUser.getImage04());
		if(resources4 !=null){
		 image04Path = resources4.getFilePath() + File.separator + resources4.getId()+ resources4.getExeName();
		}
		Resources resources5 = new Resources();
		String image05Path="";
		resources5 = this.registerUserService.get(Resources.class, rUser.getImage05());
		if(resources5 !=null){
		image05Path = resources5.getFilePath() + File.separator + resources5.getId()+ resources5.getExeName();
		}
		List<RegisterCategory> registerCategories = registerUserService.getRegisterCategoryById(rUser.getId());
		mv.addObject("RegisterCategory", registerCategories);
		mv.addObject("register", rUser);
		mv.addObject("image01Path", image01Path);
		mv.addObject("image02Path", image02Path);
		mv.addObject("image03Path", image03Path);
		mv.addObject("image04Path", image04Path);
		mv.addObject("image05Path", image05Path);
		mv.setViewName("register/register-edit");
		return mv;
	}
	
	/**
	 * @description 修改注册用户信息(user)
	 * @author shy
	 * @param
	 */
	@RequestMapping("/editPageUser")
	@ResponseBody
	public ModelAndView editPageUser(HttpSession session) {
		ModelAndView mv = new ModelAndView();
		User  u =(User) session.getAttribute("loginUser");
		RegisterUser rUser = registerUserService.getRegisterById(u.getRegisterId());	
		Resources resources = new Resources();	
		String image01Path="";
		resources = this.registerUserService.get(Resources.class, rUser.getImage01());
		if(resources !=null){
			 image01Path = resources.getFilePath() + File.separator + resources.getId()+ resources.getExeName();	
		}
		
		Resources resources2 = new Resources();
		String image02Path="";
		resources2 = this.registerUserService.get(Resources.class, rUser.getImage02());
		if(resources !=null){
		  image02Path = resources2.getFilePath() + File.separator + resources2.getId()+ resources2.getExeName();
		}
		Resources resources3 = new Resources();
		String image03Path="";
		resources3 = this.registerUserService.get(Resources.class, rUser.getImage03());
		if(resources3 !=null){
		image03Path = resources3.getFilePath() + File.separator + resources3.getId()+ resources3.getExeName();
		}
		Resources resources4 = new Resources();
		String image04Path="";
		resources4 = this.registerUserService.get(Resources.class, rUser.getImage04());
		if(resources4 !=null){
		 image04Path = resources4.getFilePath() + File.separator + resources4.getId()+ resources4.getExeName();
		}
		Resources resources5 = new Resources();
		String image05Path="";
		resources5 = this.registerUserService.get(Resources.class, rUser.getImage05());
		if(resources5 !=null){
		image05Path = resources5.getFilePath() + File.separator + resources5.getId()+ resources5.getExeName();
		}
		List<RegisterCategory> registerCategories = registerUserService.getRegisterCategoryById(rUser.getId());
		mv.addObject("RegisterCategory", registerCategories);
		mv.addObject("register", rUser);
		mv.addObject("image01Path", image01Path);
		mv.addObject("image02Path", image02Path);
		mv.addObject("image03Path", image03Path);
		mv.addObject("image04Path", image04Path);
		mv.addObject("image05Path", image05Path);
		mv.setViewName("register/register-edit2");
		return mv;
	}
	
	/**
	 * @description 进入修改密码页面
	 * @author shy
	 */
	@RequestMapping("/editPasswordPage")
	@ResponseBody
	public ModelAndView editPasswordPage(){
		ModelAndView mv = new ModelAndView();
        mv.setViewName("register/pwd-edit");
		return mv;
	}
	
	
	/**
	 * @description 密码修改
	 * @author shy
	 * @throws IOException 
	 */
	@RequestMapping("/editpwd")
	@ResponseBody
	public void editPassword(HttpSession session, String passWord, String newpassWord,HttpServletResponse resp) throws IOException {
		String result="";
		User user = (User)session.getAttribute("loginUser");
		String loginName = user.getLoginName();
		User loginUser = null;
		RegisterUser registerUser = null;
		List<RegisterUser> registerUsers=this.registerUserService.getLoginRegisterUserByLoginName(loginName);
		List<User> users = this.userService.getLoginUser(loginName);
		if(registerUsers.size()>0){
			for (RegisterUser regUser : registerUsers) {
				if (regUser.getPwd().equals(MD5Lock.lock(passWord.trim()))) {
					registerUser = regUser;
					registerUser.setPwd(MD5Lock.lock(newpassWord));
					this.registerUserService.saveOrUpdate(registerUser);
					if(users.size()>0){
						loginUser=users.get(0);
						loginUser.setPsw(MD5Lock.lock(newpassWord));
						this.userService.saveOrUpdate(loginUser);
						}
					result=Constant.SAVE_SUCCESS;
					resp.getWriter().print(result);
				}else{
					// return Constant.PSW_NO_RIGNT;
					result=Constant.PSW_NO_RIGNT;
					resp.getWriter().print(result);
				  }
				}
			}else{
				   // return Constant.USER_NO_EXIST;//用户不存在
				    result=Constant.USER_NO_EXIST;
				    resp.getWriter().print(result);
			}	
				
		}
	
	
}
